An exception is an event that disrupts normal flow of the program at runtime.
Imagine you're using an ATM:
int a = 10; int b = 0; int result = a / b; // โ ArithmeticException: divide by zero
The Throwable
class is the root of Javaโs exception hierarchy. Every
exception or error object in Java is a subclass of Throwable
.
The Exception
class represents problems that can be handled programmatically.
try-catch
or declared with throws
.IOException
SQLException
ClassNotFoundException
ArithmeticException
NullPointerException
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
The Error
class indicates serious problems that applications should not attempt to catch.
StackOverflowError
VirtualMachineError
OutOfMemoryError
(not shown but common)try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the specific exception
} finally {
// Code that always executes (cleanup, closing files, etc.)
}
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!"); // This will run
} finally {
System.out.println("Cleanup done!"); // This will always run
}
๐ Output:
Cannot divide by zero!
Cleanup done!
๐ Note: The finally
block will always execute whether an exception is
thrown or not. It's used to release resources like file handles, database connections, etc.
๐ง Hinglish Explanation:
throw
ka use tab karte hain jab aap manually exception throw karna
chahte ho.throws
ka use method ke signature mein hota hai, jahan aap declare
karte ho ki method exception throw kar sakta hai.Keyword | Meaning | Used In |
---|---|---|
throw |
Used to manually throw an exception | Inside method body |
throws |
Used to declare that a method may throw an exception | In method signature |
throw
void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Invalid age: must be 18 or above");
}
System.out.println("Valid age!");
}
Output: Agar age 15 hai to: Invalid age: must be 18 or above
throws
import java.io.*;
void readFile() throws IOException {
FileReader fr = new FileReader("file.txt");
// This may throw IOException
}
Note: Method ke signature mein throws IOException
likhne se compiler ko
pata chalta hai ki is method mein exception aa sakta hai.
๐ก Tip: Aksar interview mein yeh puchte hain: "throw vs throws difference?"
Answer: throw
ka use exception ko actually throw karne ke liye hota hai,
jabki throws
batata hai ki method se exception aa sakta hai.
Create your own exception class:
class AgeException extends Exception { AgeException(String msg) { super(msg); } }
Use it:
if (age < 18) { throw new AgeException("Not eligible"); }
๐ง Hinglish Explanation:
final
: Jo cheez fix karni ho (no change allowed)finally
: try-catch ke baad hamesha chalega (cleanup)finalize()
: Jab object destroy hone wala ho, GC ke time call hota hai (โ ๏ธ deprecated
after Java 9)Keyword | Use |
---|---|
final |
Prevent change (used with variables, methods, class) |
finally |
Always runs after try-catch (cleanup) |
finalize() |
Called by Garbage Collector before destroying object (deprecated) |
class Demo {
protected void finalize() throws Throwable {
System.out.println("๐๏ธ Object is being destroyed by GC");
}
}
public class Test {
public static void main(String[] args) {
Demo obj = new Demo();
obj = null; // make eligible for GC
System.gc(); // request garbage collection
System.out.println("Main complete");
}
}
๐ Output ho sakta hai: Main complete ke baad finalize() message aaye
โ ๏ธ Note: finalize()
is deprecated in Java 9+. Use
AutoCloseable
or try-with-resources instead.
Automatically closes resources like files or DB connections.
try (FileReader fr = new FileReader("data.txt")) { // use file } catch (IOException e) { e.printStackTrace(); }
Concept | Notes |
---|---|
Throwable | Base class of Error & Exception |
Checked Exception | Must handle using try-catch or throws |
Unchecked | Occurs at runtime |
throw | Manually throw exception |
throws | Declare possible exception |
finally | Always executes for cleanup |
finalize() | Called by GC (now deprecated) |
โ
Checked: Must be handled (IOException
)
โ Unchecked: Runtime errors (NullPointerException
)
throw
and throws
?throw
: throw exception manuallythrows
: declare in method signature